package com.uziot.bucket.mdc.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Set;

/**
 * 功能描述: <br>
 * 业务日志类
 *
 * @author shidt
 * @date 2019-11-07 16:19
 */
public class LogUtils {
    /**
     * 业务流水日志
     *
     * @param method 方法
     * @param type   如 请求：request，响应：response，异常：exception
     * @return 记录串拼接
     */
    public static String logTrace(String method, String type, Map<String, String> map, String message) {
        //mdc 属性
        StringBuilder sb = new StringBuilder();
        Map<String, String> mdcMap = MDC.getCopyOfContextMap();
        if (mdcMap != null) {
            Set<String> keys = mdcMap.keySet();
            for (String key : keys) {
                sb.append(key).append("=").append(mdcMap.get(key)).append("|");
            }
        }

        //自定义属性
        Set<String> keys1 = map.keySet();
        StringBuilder sb1 = new StringBuilder();
        for (String key : keys1) {
            sb1.append(key).append("=").append(map.get(key)).append("|");
        }

        String msg;
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            if (jsonObject != null) {
                jsonObject.remove("fileBytes");
                jsonObject.remove("bytes");
                jsonObject.remove("requestData");
                msg = JSONObject.toJSONString(jsonObject);
            } else {
                msg = message;
            }
        } catch (Exception e) {
            msg = message;
        }

        return "|" + "method=" + method + "|" + "type=" + type + "|" + sb.toString() + "|" + sb1.toString() + "|" + "message=" + msg;
    }


    /**
     * @param method  method
     * @param request request
     * @return String
     */
    public static String logRequestInit0(String method, String request) {
        return "|" + "method=" + method + "|" + "type=init" + "|" + request;
    }
}
